package com.bodacn.keypoint;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

public class QueryActivity extends AppCompatActivity implements View.OnClickListener {
    private String TAG=this.getClass().getName();
    private final int MSG_DetailOver=1001;
    private final int MSG_HeadOver =1002;
    private final int MSG_GetDetail=1003;
    String STORE_NAME = "Settings";
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,CPUID;
    String curOrderNo,curStyleNo,curStyleSort,QueryTitle;
    Button btn_Query,btn_QueryQty,btn_Return;
    ListView detailList;
    TextView txt_Title;
    EditText edt_StartDate,edt_EndDate,edt_StyleNo;
    LinearLayout querylisthead;
    JSONArray detailJson,headJson;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_query);

        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curDepartNo=paramBundle.getString("CurDepartNO");
        curDepart=paramBundle.getString("CurDepart");
        curServiceUrl=paramBundle.getString("ServiceUrl");
        curServiceDir=paramBundle.getString("ServiceDir");
        CPUID=paramBundle.getString("CPUID");
        //界面信息
        QueryTitle=paramBundle.getString("QueryTitle");
        curOrderNo=paramBundle.getString("OrderNo");
        curStyleNo=paramBundle.getString("StyleNo");
        curStyleSort=paramBundle.getString("StyleSort");
        System.out.println(paramBundle);
        //初始化界面
        txt_Title=findViewById(R.id.txt_Title);
        txt_Title.setText(QueryTitle);
        btn_Query=findViewById(R.id.btn_Query);
        btn_Query.setOnClickListener(this);
        btn_QueryQty=findViewById(R.id.btn_QueryQty);
        btn_QueryQty.setOnClickListener(this);
        btn_Return=findViewById(R.id.btn_Return);
        btn_Return.setOnClickListener(this);
        detailList=findViewById(R.id.detailList);
        //列表头;
        querylisthead=findViewById(R.id.querylisthead);
        edt_StyleNo=findViewById(R.id.edt_StyleNo);
        //文本框
        edt_StartDate = findViewById(R.id.edt_StartDate);
        edt_StartDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog mDialog = new DatePickerDialog(v.getContext(), null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                mDialog .setButton(DialogInterface.BUTTON_POSITIVE,"完成",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar.set(year,month,day);
                        edt_StartDate.setText(DateFormat.format("yyyy-MM-dd", calendar));
                    }
                });
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE,"取消",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog.setTitle("选择查询起始日期");
                mDialog.show();

            }
        });
        edt_StartDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d("edit_startDate","onFocusChange");
                if (hasFocus == true) {
                    hideIM(v);
                }
            }
        });
        edt_EndDate = findViewById(R.id.edt_EndDate);
        edt_EndDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog mDialog = new DatePickerDialog(v.getContext(), null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                mDialog .setButton(DialogInterface.BUTTON_POSITIVE,"完成",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar.set(year,month,day);
                        edt_EndDate.setText(DateFormat.format("yyyy-MM-dd", calendar));
                    }
                });
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE,"取消",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog.setTitle("选择查询截止日期");
                mDialog.show();
            }
        });

        //置日期初始值;
        Date curDate = new Date(System.currentTimeMillis());
        SharedPreferences settings = this.getSharedPreferences(STORE_NAME, getApplicationContext().MODE_PRIVATE);
        String EndDateStr=(String) DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime()));
        edt_StartDate.setText(EndDateStr);
        edt_EndDate.setText(EndDateStr);


    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getApplicationContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }
    public  String TransValue(String params)
    {
        if (params.toUpperCase().equals("NULL")||params.equals("0")||params.equals("0.0"))
            return "";
        else return params;
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            case R.id.btn_Query:
                GetHeadList("Output");
                break;
            case R.id.btn_QueryQty:
                GetHeadList("Quality");
                break;
            case R.id.btn_Return:
                finish();
                break;

            default:
                break;
        }

    }

    //获取明细;
    private void GetDetail(String paramType) {
        String sqlCmd="Exec KeyPoint_Query @OperType='Query',@QueryTitle='"+QueryTitle+"',@QueryType='"+paramType+"',@StartDate='"+edt_StartDate.getText().toString()+"',@EndDate='"
                +edt_EndDate.getText().toString()+"',@StyleNo='"+edt_StyleNo.getText().toString()+"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        ReadSQLData(sqlCmd);
    }

    //提交所选择的工序至服务器,然后刷新工序列表;
    private void GetHeadList(final String paramType) {
        try {
            headJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Runnable run = new Runnable() {
            @Override
            public void run() {
                //将数据读到JSONArray;
                try {
                    String sqlcmd="Exec KeyPoint_Query @OperType='Title',@QueryType='"+paramType+"',@QueryTitle='"+QueryTitle+"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
                    Statement stmt = ToolUtil.getSQLConnection().createStatement();
                    ResultSet rs = stmt.executeQuery(sqlcmd);
                    //取字段相关信息;
                    ResultSetMetaData metaData = rs.getMetaData();
                    int columnCount = metaData.getColumnCount();
                    //遍列数据;
                    while (rs.next()) {
                        JSONObject jsonObj = new JSONObject();
                        // 遍历每一列
                        for (int i = 1; i <= columnCount; i++) {
                            String columnName = metaData.getColumnLabel(i);
                            Object value = rs.getObject(columnName);
                            if (value==null) value="";
                            jsonObj.put(columnName, value);
                        }
                        headJson.put(jsonObj);
                    }
                    //显示预排单;
                    Message msg = new Message();
                    msg.what = MSG_HeadOver;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                    //消息给创建列;
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }catch (Exception e){
                    e.printStackTrace();
                }


            }
        };
        new Thread(run).start();
    }

    //创建列;
    private void CreateListHead() {
        //内容为表头，宽度，自适应;
        if ((headJson != null) && (headJson.length() > 0)) {
            int childCount = querylisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = querylisthead.getChildAt(i);
                if (view instanceof TextView) {
                    querylisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom;
            for (int i=0;i<headJson.length();i++)
                if (headJson.optJSONObject(i).has("TitleText") == true) {
                    try {
                        TitleName = headJson.optJSONObject(i).getString("TitleName");
                        TitleText = headJson.optJSONObject(i).getString("TitleText");
                        TxtSize = headJson.optJSONObject(i).getInt("TxtSize");
                        txtWidth = headJson.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = headJson.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(this);
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.text_main));
                        tv.setGravity(Gravity.CENTER_VERTICAL);
                        tv.setTextSize(TxtSize);
                        //添加到View中;
                        if (AutoZoom==1) querylisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else querylisthead.addView(tv);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            querylisthead.postInvalidate();
            //发消息查明细;
            Message msg = new Message();
            msg.what = MSG_GetDetail;
            handler.removeMessages(msg.what);
            handler.sendMessage(msg);
        }
    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData ( final String SQLComm){
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    JSONArray jsonArray = ToolUtil.QuerySQL2JSON(SQLComm);
                    //往界面转数据;
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        if (jsonArray.optJSONObject(0).has("OperType") == true) {
                            //呼叫信息及库存警告
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("Query") == true) {
                                detailJson = jsonArray;
                                //显示预排单;
                                Message msg = new Message();
                                msg.what = MSG_DetailOver;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        };
        new Thread(run).start();

    }



    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case MSG_HeadOver:
                    //创建列;
                    CreateListHead();
                    break;
                case MSG_GetDetail:
                    //创建列;
                    String QueryType="Output";
                    if ((headJson!=null)&&(headJson.optJSONObject(0).has("QueryType")==true)){
                        try {
                            QueryType=headJson.optJSONObject(0).getString("QueryType");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    GetDetail(QueryType);
                    break;
                case MSG_DetailOver:
                    System.out.println(detailJson);
                    //显示明细数据
                    DetailListAdapter detailListAdapter=new DetailListAdapter(getApplicationContext());
                    detailList.setAdapter(detailListAdapter);
                    break;
                default:
                    break;
            }
        }
    };

    //获取颜色
    private int TransColor(String paramColorStr){
        int rtn=0;
        if ((paramColorStr.indexOf("#")==0)&&(paramColorStr.length()>=7)){
            rtn=Color.parseColor(paramColorStr);
        }else {
            if (isNumer(paramColorStr)) {
                int testColor = Integer.parseInt(paramColorStr);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                rtn = Color.rgb(red, green, blue);
            } else {
                if (paramColorStr.equals("Black") == true)
                    rtn = Color.BLACK;
                if (paramColorStr.equals("Blue") == true)
                    rtn = Color.BLUE;
                if (paramColorStr.equals("Yellow") == true)
                    rtn = Color.YELLOW;
                if (paramColorStr.equals("Red") == true)
                    rtn = Color.RED;
                if (paramColorStr.equals("Green") == true)
                    rtn = Color.GREEN;
                if (paramColorStr.equals("Gray") == true)
                    rtn = Color.LTGRAY;
                if (paramColorStr.equals("White") == true)
                    rtn = Color.WHITE;
            }

        }
        return rtn;
    }

    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    //订单表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_query_listhead, null, false);
            //if (convertView == null) convertView = inflater.inflate(R.layout.activity_query_listhead, null, false);
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,38));
            int color = getResources().getColor(R.color.text_black);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                if (detailJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = detailJson.optJSONObject(position).getString("ConColor");
                    color=TransColor(tmpValue);
                }
                for (int i = 0; i < headJson.length(); i++)
                    if (headJson.optJSONObject(i).has("TitleText") == true) {
                        try {
                            String TitleName = headJson.optJSONObject(i).getString("TitleName");
                            if (detailJson.optJSONObject(position).has(TitleName)==true) tmpValue= detailJson.optJSONObject(position).getString(TitleName);
                            else tmpValue="unReturn";
                            int TxtSize = headJson.optJSONObject(i).getInt("TxtSize");
                            float txtWidth = headJson.optJSONObject(i).getLong("TxtWidth");
                            int AutoZoom = headJson.optJSONObject(i).getInt("AutoZoom");
                            TextView tv = new TextView(view.getContext());
                            tv.setText(tmpValue);
                            tv.setWidth((int) txtWidth);
                            tv.setTextColor(color);
                            tv.setGravity(Gravity.CENTER_VERTICAL);
                            tv.setTextSize(TxtSize);
                            //添加到View中;
                            if (AutoZoom == 1)
                                ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                            else ((LinearLayout)view).addView(tv);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailListAdapter_position:"+position);
            return view;
        }
    }

}
